import config from "@/common/config";
import api from "@/api/API";
import wmx from '@/common/wmx';
const env = process.env.NODE_ENV === "development";

export default {
  //加载
  install(app) {
    let instance = this.init();
    app.config.globalProperties.$api = instance.$api;
  },
  // 初始化
  init() {
    let proxy = wmx.app.config.globalProperties;
    async function $api(
      name,
      data = {},
      loading_visible = true,
      toast_visible = true,
      methods = 'POST'
    ) {
      let server = config.default_service; /** 服务环境*/
      server.headers['token'] = proxy.$store.token ? proxy.$store.token : ''
      server.headers['deviceId'] = proxy.$store.sys && proxy.$store.sys.deviceId ? proxy.$store.sys.deviceId : ''
      
      return new Promise((resolve, reject) => {
        if (loading_visible) {
          uni.showLoading({
            title: "加载中",
          });
        }
        let domain = ''
        domain = (env ? server.base_url_dev : server.base_url_prod)
        uni.request({
          url: domain + api[name],
          data: data,
          header: server.headers,
          method: methods,
          success: (res) => {
            uni.hideLoading();
            // 生产环境加密
            if (res.statusCode === 200) {
              if (res.data.code === 202) {
                /** 登录过期，token失效 */
                proxy.$store.token = ''
                proxy.$store.user_info = {}
                uni.switchTab({
                  url: "/pages/tabs/index/index",
                });
              } else if (res.data.code !== 0) {
                /** 默认显示报错提示*/
                if (toast_visible) {
                  error_toast(res.data.message);
                }
              }
              resolve(res.data);
            } else {
              if (toast_visible) {
                error_toast(res.data.message);
              }
              resolve({ code: res.code || 1, data: res });
            }
          },
          fail: (err) => {
            if (toast_visible) {
              error_toast();
            }
            return reject(err);
          },
        });
      });
    }

    function error_toast(msg = "网络异常，请稍候重试") {
      uni.showToast({
        title: msg,
        icon: "none",
        duration: 3000,
      });
    }

    //返回实例
    return {
      $api,
    };
  },
};
